

<template>
    <div class="login-box-modal">
        <el-dialog
        v-model="loginDialogConfig.showLogin"
        width="580"
        :show-close="false"
        class="login-modal"
        :before-close="handleClose"
    >
            <div v-if="state.showRetrievePasswordDialog==false">
                <div style="display: flex;flex-direction: row-reverse;">
                    <div style="background: #185de1;    width: 200px;    border-radius: 30px;">
                        <el-icon @click="handleClose" size="18" style="    position: relative;    right: 20px;    float: right;    top: 20px;    cursor: pointer;    color: #fff;"><CircleClose /></el-icon>
                    </div>
                    <div class="login-box">
                        <div class="login-title">{{state.form.tab=='login'?'登录':'注册'}} </div>
                        <el-form ref="formRef" @keyup.enter="onSubmitPre" :rules="rules" :model="state.form">
                            <!-- 注册验证方式 -->
                            <el-form-item v-if="state.form.tab == 'show'">
                                <el-radio-group size="large" v-model="state.form.registerType">
                                    <el-radio
                                        class="register-verification-radio"
                                        value="email"
                                        :disabled="!state.accountVerificationType.includes('email')"
                                        border
                                    >
                                        {{ t('Via email') + t('register') }}
                                    </el-radio>
                                    <el-radio
                                        class="register-verification-radio"
                                        value="mobile"
                                        :disabled="!state.accountVerificationType.includes('mobile')"
                                        border
                                    >
                                        {{ t('Via mobile number') + t('register') }}
                                    </el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <!-- 登录注册用户名 -->
                            <el-form-item prop="mobile" v-if="state.form.tab == 'login'">
                                <el-input
                                    v-model="state.form.mobile"
                                    :placeholder="
                                            state.form.tab == 'register'
                                                ? t('Please input field', { field: t('User name') })
                                                : t('Please input field', { field: t('mobile') })
                                        "
                                    :clearable="true"
                                    size="large"
                                >
                                    <template #prefix>
                                        <Icon name="fa fa-user" size="16" color="var(--el-input-icon-color)" />
                                    </template>
                                </el-input>
                            </el-form-item>
                            <!-- 注册手机号 -->
                            <el-form-item v-if="state.form.tab == 'register' && state.form.registerType == 'mobile'" prop="mobile">
                                <el-input
                                    v-model="state.form.mobile"
                                    :placeholder="t('Please input field', { field: t('mobile') })"
                                    :clearable="true"
                                    size="large"
                                >
                                    <template #prefix>
                                        <Icon name="fa fa-tablet" size="16" color="var(--el-input-icon-color)" />
                                    </template>
                                </el-input>
                            </el-form-item>

                            <!-- 注册验证码 -->
                            <el-form-item v-if="state.form.tab == 'register'" prop="captcha">
                                <el-row class="w100">
                                    <el-col :span="16">
                                        <el-input
                                            size="large"
                                            v-model="state.form.captcha"
                                            :placeholder="t('Please input field', { field: t('Verification Code') })"
                                            autocomplete="off"
                                        >
                                            <template #prefix>
                                                <Icon name="fa fa-ellipsis-h" size="16" color="var(--el-input-icon-color)" />
                                            </template>
                                        </el-input>
                                    </el-col>
                                    <el-col class="captcha-box" :span="8">
                                        <el-button
                                            size="large"
                                            @click="sendRegisterCaptchaPre"
                                            :loading="state.sendCaptchaLoading"
                                            :disabled="state.codeSendCountdown <= 0 ? false : true"
                                            type="primary"
                                        >
                                            {{
                                                state.codeSendCountdown <= 0
                                                    ? t('send')
                                                    : state.codeSendCountdown + t('seconds')
                                            }}
                                        </el-button>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <el-form-item v-if="state.form.tab == 'register' " prop="nickname">
                                <el-input placeholder="请输入姓名"  size="large" v-model="state.form.nickname">
                                    <template #prefix>
                                        <el-icon><User /></el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item v-if="state.form.tab == 'register' " prop="group_id">
                                <el-select   size="large" class="group-select" v-model="state.form.group_id" placeholder="请选择分组">
                                    <template #prefix>
                                        <Icon name="fa fa-users" size="16" color="var(--el-input-icon-color)" />
                                    </template>
                                    <el-option
                                        v-for="item in state.userGroup"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                            <!-- 登录注册密码 -->
                            <el-form-item prop="password">
                                <el-input
                                    v-model="state.form.password"
                                    :placeholder="t('Please input field', { field: t('password') })"
                                    type="password"
                                    show-password
                                    size="large"
                                >
                                    <template #prefix>
                                        <Icon name="fa fa-unlock-alt" size="16" color="var(--el-input-icon-color)" />
                                    </template>
                                </el-input>
                            </el-form-item>

                            <!-- 注册邮箱 -->
                            <el-form-item v-if="state.form.tab == 'register' && state.form.registerType == 'email'" prop="email">
                                <el-input
                                    v-model="state.form.email"
                                    :placeholder="t('Please input field', { field: t('email') })"
                                    :clearable="true"
                                    size="large"
                                >
                                    <template #prefix>
                                        <Icon name="fa fa-envelope" size="16" color="var(--el-input-icon-color)" />
                                    </template>
                                </el-input>
                            </el-form-item>

                            <div  class="form-footer"  v-if="state.form.tab == 'login'">
                                <div @click="state.showRetrievePasswordDialog = true" class="forgot-password">
                                   忘记密码？找回密码
                                </div>
                            </div>
                            <el-form-item class="form-buttons" v-if="state.form.tab == 'register'">
                                <div style="display: flex;justify-content: space-evenly;">
                                    <div style="flex: 2" >
                                        <el-button style="width: 155px;background: #066bf7;color:#ffffff"
                                                   class="login-btn"
                                                   @click="onSubmitPre"
                                                   :loading="state.formLoading"
                                                   round
                                                   type="primary"
                                                   size="large">提交</el-button>
                                    </div>
                                    <div style="width: 30px"></div>
                                    <div style="flex: 1" >
                                        <el-button style="width: 155px;"
                                                   class="login-btn"
                                                   link
                                                   @click="state.form.tab='login'"
                                                   round plain size="large">
                                            返回
                                        </el-button>
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item class="form-buttons" v-if="state.form.tab == 'login'">
                                <div style="display: flex;justify-content: space-evenly;">
                                    <div style="flex: 3">
                                        <el-button style="width: 155px;background: #066bf7;"
                                                   class="login-btn"
                                                   @click="onSubmitPre"
                                                   :loading="state.formLoading"
                                                   round
                                                   type="primary"
                                                   size="large"
                                        >登录</el-button>
                                    </div>
                                    <div style="width: 30px"></div> <div style="flex: 1" >
                                    <el-button style="width: 155px;"
                                               :disabled="chatInfoObj.$state.loginset==1||chatInfoObj.$state.loginset==3"
                                               class="login-btn" link
                                               @click="changeType('register')"
                                               round plain size="large">
                                        注册
                                    </el-button>
                                </div>

                                </div>
                                <div style="color: #999999; margin-top: 20px">*登录即表示同意<a style="color: #066bf7;">《用户协议》</a></div>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </div>
            <div class="retrieve-password-form " style="padding: 10px 60px;display: flex;    flex-direction: column;" v-if="state.showRetrievePasswordDialog">
                <div class="login-title">找回密码</div>
                <el-form
                        ref="retrieveFormRef"
                        @keyup.enter="onSubmitRetrieve()"
                        :rules="retrieveRules"
                        :model="state.retrievePasswordForm"
                        :label-width="100"
                    >
                        <el-form-item :label="t('Retrieval method')" v-show="false">
                            <el-radio-group v-model="state.retrievePasswordForm.type">
                                <el-radio value="email" :disabled="!state.accountVerificationType.includes('email')" border>
                                    {{ t('Via email') }}
                                </el-radio>
                                <el-radio value="mobile" :disabled="!state.accountVerificationType.includes('mobile')" border>
                                    {{ t('Via mobile number') }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item prop="account" :label="state.retrievePasswordForm.type == 'email' ? t('email') : t('mobile')">
                            <el-input
                                autocomplete="off"
                                v-model="state.retrievePasswordForm.account"
                                :placeholder="
                                t('Please input field', {
                                    field: state.retrievePasswordForm.type == 'email' ? t('email') : t('mobile'),
                                })
                            "
                                :clearable="true"
                            >
                                <template #prefix>
                                    <Icon name="fa fa-user" size="16" color="var(--el-input-icon-color)" />
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="captcha" :label="t('Verification Code')">
                            <el-row class="w100">
                                <el-col :span="16">
                                    <el-input
                                        v-model="state.retrievePasswordForm.captcha"
                                        :placeholder="t('Please input field', { field: t('Verification Code') })"
                                        autocomplete="off"
                                    >
                                        <template #prefix>
                                            <Icon name="fa fa-ellipsis-h" size="16" color="var(--el-input-icon-color)" />
                                        </template>
                                    </el-input>
                                </el-col>
                                <el-col class="captcha-box" :span="8">
                                    <el-button
                                        @click="sendRetrieveCaptchaPre"
                                        :loading="state.sendCaptchaLoading"
                                        :disabled="state.codeSendCountdown <= 0 ? false : true"
                                        type="primary"
                                    >
                                        {{ state.codeSendCountdown <= 0 ? t('send') : state.codeSendCountdown + t('seconds') }}
                                    </el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item prop="password" :label="t('New password')">
                            <el-input
                                v-model="state.retrievePasswordForm.password"
                                autocomplete="off"
                                :placeholder="t('Please input field', { field: t('New password') })"
                                show-password
                            >
                                <template #prefix>
                                    <Icon name="fa fa-unlock-alt" size="16" color="var(--el-input-icon-color)" />
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="state.showRetrievePasswordDialog = false">{{ t('Cancel') }}</el-button>
                            <el-button :loading="state.submitRetrieveLoading" @click="onSubmitRetrieve()" type="primary">
                                {{ t('second') }}
                            </el-button>
                        </el-form-item>
                    </el-form>
            </div>
    </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import {CircleClose} from '@element-plus/icons-vue'
import { reactive, onMounted, onUnmounted,watch} from 'vue'
import { sendEms, sendSms } from '@/api/common'
import { uuid } from '@/utils/random'
import { useI18n } from 'vue-i18n'
import { buildValidatorData, validatorAccount } from '@/utils/validate'
import { checkIn, retrievePassword } from '@/api/user/index'
import { useEventListener } from '@vueuse/core'
import { onResetForm } from '@/utils/common'
import { useUserInfo } from '@/stores/userInfo'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import type { FormItemRule, FormInstance } from 'element-plus'
import clickCaptcha from '~/composables/clickCaptcha'
import {chatInfo} from "~/stores/chatinfo";
import{User,Setting} from "@element-plus/icons-vue";
let timer: number

let loginDialogConfig=inject('loginDialogConfig',{showLogin:false})
const chatInfoObj=chatInfo()
const handleClose = (done: () => void) => {
    loginDialogConfig.showLogin=false
}
interface Props {
    showIcon?: boolean
    loginDialog:boolean
}
const changeType=(type:any)=>{
    state.form.tab=type
    state.form.mobile=''
    state.form.captcha=''
    state.form.password=''
}

const props = withDefaults(defineProps<Props>(), {
    showIcon:true,
    loginDialog: false,
})
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const userInfo = useUserInfo()

let dialogVisible = ref(props.loginDialog)
if(userInfo.getToken()){
    dialogVisible.value = false
}
const formRef = ref<FormInstance>()
const retrieveFormRef = ref<FormInstance>()

interface State {
    form: {
        tab: 'login' | 'register'
        email: string
        mobile: string
        username: string
        password: string
        captcha: string
        keep: boolean
        captchaId: string
        captchaInfo: string
        registerType: 'email' | 'mobile'
        group_id:number
        nickname:string
    }
    formLoading: boolean
    showRetrievePasswordDialog: boolean
    retrievePasswordForm: {
        type: 'email' | 'mobile'
        account: string
        captcha: string
        password: string
    }
    dialogWidth: number
    accountVerificationType: string[]
    codeSendCountdown: number
    submitRetrieveLoading: boolean
    sendCaptchaLoading: boolean
    to: string
    userGroup:string[]
}

const state: State = reactive({
    form: {
        tab: 'login',
        email: '',
        mobile: '',
        username: '',
        password: '',
        captcha: '',
        keep: false,
        captchaId: uuid(),
        captchaInfo: '',
        registerType: 'mobile',
        group_id:0,
        nickname:''
    },
    formLoading: false,
    showRetrievePasswordDialog: false,
    retrievePasswordForm: {
        type: 'mobile',
        account: '',
        captcha: '',
        password: '',
    },
    dialogWidth: 36,
    accountVerificationType: [],
    codeSendCountdown: 0,
    submitRetrieveLoading: false,
    sendCaptchaLoading: false,
    // 登录成功后要跳转的URL
    to: route.query.to as string,
    userGroup:[]
})

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    email: [
        buildValidatorData({ name: 'required', title: t('email') }),
        buildValidatorData({ name: 'email', title: t('email') }),
    ],
    username: [
        buildValidatorData({ name: 'required', title: t('User name') }),
        {
            validator: (rule: any, val: string, callback: Function) => {
                if (state.form.tab == 'register') {
                    return validatorAccount(rule, val, callback)
                } else {
                    callback()
                }
            },
            trigger: 'blur',
        },
    ],
    password: [buildValidatorData({ name: 'required', title: t('password') }), buildValidatorData({ name: 'password' })],
    mobile: [buildValidatorData({ name: 'required', title: t('mobile') }), buildValidatorData({ name: 'mobile' })],
    captcha: [buildValidatorData({ name: 'required', title: t('Verification Code') })],
})

const retrieveRules: Partial<Record<string, FormItemRule[]>> = reactive({
    account: [buildValidatorData({ name: 'required', title: t('Account name') })],
    captcha: [buildValidatorData({ name: 'required', title: t('Verification Code') })],
    password: [buildValidatorData({ name: 'required', title: t('password') }), buildValidatorData({ name: 'password' })],
})

const resize = () => {
    let clientWidth = document.documentElement.clientWidth
    let width = 36
    if (clientWidth <= 790) {
        width = 92
    } else if (clientWidth <= 910) {
        width = 56
    } else if (clientWidth <= 1260) {
        width = 46
    }
    state.dialogWidth = width
}

const onSubmitPre = () => {
    formRef.value?.validate((valid) => {
        if (!valid) return
        if (state.form.tab == 'login') {
            clickCaptcha(state.form.captchaId, (captchaInfo: string) => onSubmit(captchaInfo))
        } else {
            onSubmit()
        }
    })
}
const onSubmit = (captchaInfo = '') => {
    state.formLoading = true
    state.form.captchaInfo = captchaInfo
    checkIn('post', state.form)
        .then((res) => {
            if (res.code != 1) return
            userInfo.dataFill(res.data.userInfo)
            setTimeout(() => {
               window.location.reload()
            },200)
            //window.location.reload()
            // if (state.to) return (location.href = state.to)
            // router.push({ path: res.data.routePath })
        }).catch(() => {
            state.formLoading = false
        })
        .finally(() => {
            state.formLoading = false
        })
}
const onSubmitRetrieve = () => {
    if (!retrieveFormRef.value) return
    retrieveFormRef.value.validate((valid) => {
        if (valid) {
            state.submitRetrieveLoading = true
            retrievePassword(state.retrievePasswordForm)
                .then((res) => {
                    state.submitRetrieveLoading = false
                    if (res.code == 1) {
                        state.showRetrievePasswordDialog = false
                        endTiming()
                        onResetForm(retrieveFormRef.value)
                    }
                })
                .catch(() => {
                    state.submitRetrieveLoading = false
                })
        }
    })
}

const sendRegisterCaptchaPre = () => {
    if (state.codeSendCountdown > 0) return
    formRef.value!.validateField([state.form.registerType, 'username', 'password']).then((valid) => {
        if (!valid) return
        clickCaptcha(state.form.captchaId, (captchaInfo: string) => sendRegisterCaptcha(captchaInfo))
    })
}
const sendRegisterCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    const func = state.form.registerType == 'email' ? sendEms : sendSms
    func(state.form[state.form.registerType], 'user_register', {
        captchaInfo,
        captchaId: state.form.captchaId,
    })
        .then((res) => {
            if (res.code == 1) startTiming(60)
        })
        .finally(() => {
            state.sendCaptchaLoading = false
        })
}

const sendRetrieveCaptchaPre = () => {
    if (state.codeSendCountdown > 0) return
    retrieveFormRef.value!.validateField('account').then((valid) => {
        if (!valid) return
        clickCaptcha(state.form.captchaId, (captchaInfo: string) => sendRetrieveCaptcha(captchaInfo))
    })
}
const sendRetrieveCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    const func = state.retrievePasswordForm.type == 'email' ? sendEms : sendSms
    func(state.retrievePasswordForm.account, 'user_retrieve_pwd', {
        captchaInfo,
        captchaId: state.form.captchaId,
    })
        .then((res) => {
            if (res.code == 1) startTiming(60)
        })
        .finally(() => {
            state.sendCaptchaLoading = false
        })
}

const switchTab = (formRef: FormInstance | undefined = undefined, tab: 'login' | 'register') => {
    state.form.tab = tab
    if (tab == 'register') state.form.username = ''
    if (formRef) formRef.clearValidate()
}

const startTiming = (seconds: number) => {
    state.codeSendCountdown = seconds
    timer = window.setInterval(() => {
        state.codeSendCountdown--
        if (state.codeSendCountdown <= 0) {
            endTiming()
        }
    }, 1000)
}
const endTiming = () => {
    state.codeSendCountdown = 0
    if(timer){
        clearInterval(timer)
    }
}

onMounted(async () => {
    resize()
    useEventListener(window, 'resize', resize)
    if(userInfo.getToken()==''){
        checkIn('get',{},false).then((res) => {
            state.accountVerificationType = res.data.accountVerificationType
            state.retrievePasswordForm.type = res.data.accountVerificationType.length > 0 ? res.data.accountVerificationType[0] : ''
            state.userGroup=res.data.user_group
            state.form.group_id=res.data.group_id
        })
    }
    if (route.query.type == 'register') state.form.tab = 'register'
})
onUnmounted(() => {
    state.codeSendCountdown = 0
    endTiming()
})
</script>

<style scoped lang="scss">
:deep(.el-dialog){
    padding:0 !important;
    border-radius: 30px;
    .el-dialog__header{
        display: none;
    }
    :deep(.el-dialog__header){
        display: none;
    }
}
.login-modal{
    padding:0 !important;
    border-radius: 30px;
    :deep(.el-dialog__header){
        display: none;
    }
}
.login-box {
    margin: 0 auto;
    border-radius: 30px;
    padding: 10px 60px 20px 0px;
    position: relative;
    right: -60px;
    width: 450px;
    background-color: var(--ba-bg-color-overlay);
}
.login-title {
    font-weight: 800;
    font-size: var(--el-font-size-large);
    line-height: 100px;
    user-select: none;
}
:deep(.el-input--large) .el-input__wrapper {
    padding: 4px 15px;
}
.form-buttons {
    padding-top: 20px;
    .el-button {
        width: 100%;
        letter-spacing: 2px;
        font-weight: 300;
        margin-top: 20px;
        margin-left: 0;
    }
}
.register-verification-radio {
    margin-top: 10px;
}
.captcha-box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .el-button {
        width: 90%;
        height: 100%;
    }
}
.form-footer {
    display: flex;
    align-items: center;
    .forgot-password {
        color: #066bf7;
        user-select: none;
        cursor: pointer;
    }
}
.retrieve-password-form {
    display: flex;
    justify-content: center;
    margin-right: 50px;
}
@media screen and (max-width: 768px) {
    .login-box {
        width: 100%;
        margin: 0 auto;
    }
    .retrieve-password-form {
        margin-right: 0;
    }
}

// 暗黑样式
@at-root .dark {
    .form-buttons {
        .login-btn {
            --el-button-bg-color: var(--el-color-primary-light-5);
            --el-button-border-color: rgba(240, 252, 241, 0.1);
        }
    }
}
.group-select{
    :deep(.el-select__wrapper){
        min-height: 46px;
    }
}
</style>

